<?php
/**
 * Created by PhpStorm.
 * User: ASUS
 * Date: 2021/9/7
 * Time: 14:38
 */
namespace app\api\controller;
class Flinpay extends Base
{
    /**
     * @author ASUS
     * @date 2021-08-20 14:10
     * 查询flin代付余额
     */
    public function getFlinBalance()
    {
        $config = db("product")->where(["product_name"=>"flinpay"])->find();
        $url = $config['url']."/gateway/account";
        $merchantCode =  $config["mch_id"];
        $params = array(
            'merchantCode' => $merchantCode,
            'dateTime' => date("YmdHis")
        );
        ksort($params);
        $params_str = '';
        foreach ($params as $key => $val) {
            $params_str = $params_str . $val;
        }
        $sign = $this->private_key_encrypt($params_str, $config["pri_key"]);
        $params['sign'] = $sign;
        $res = http_post_flin($url,$params);
        $data = ["balance"=>$res["balance"],"freeze"=>$res["freeze"]];
        api_return(200,"成功",$data);
    }
    /**
     * @param $data
     * @param $pivate_key
     * @return string
     * @author ASUS
     * @date 2020-11-26 13:48
     * flinPay私钥格式化
     */
    private function private_key_encrypt($data, $private_key)
    {
        $private_key = '-----BEGIN PRIVATE KEY-----'."\n".$private_key."\n".'-----END PRIVATE KEY-----';
        $pi_key = openssl_pkey_get_private($private_key);
        $crypto = '';
        foreach (str_split($data, 117) as $chunk) {
            openssl_private_encrypt($chunk, $encryptData, $pi_key);
            $crypto .= $encryptData;
        }
        return base64_encode($crypto);
    }
    /**
     * @author ASUS
     * @date 2021-09-07 14:40
     * flinpay代付
     */
    public function df()
    {
        $post = file_get_contents('php://input');//接受的post数据
        $param = json_decode($post, true);//转成数组
        if(empty($param)){
            $json = [
                "status"=>-1,
                "msg"=>"参数缺失",
                "data"=>[]
            ];
           return json($json);
        }
        $config = db("product")->where(["product_name"=>"flinpay"])->find();
        $url = $config['url']."/cash";//基础请求地址
        $mchId = $config["mch_id"];//商户号
        $postData = array(
            'merchantCode' => $mchId,
            'orderNum' => $param["df_orderno"],
            'money' => $param["df_amount"],
            'feeType' => 1,
            'dateTime' => date("YmdHis",time()),
            'name' => $param["user_name"],
            'number' => $param["card_no"],
            'bankCode' => $param["flin"],
            'description' => "Test Withdraw",
            'notifyUrl' => ""
        );
        ksort($postData);
        $params_str = '';
        foreach ($postData as $key => $val) {
            $params_str = $params_str . $val;
        }
        $sign = $this->private_key_encrypt($params_str, $config["pri_key"]);
        $postData['sign'] = $sign;
        $res = http_post_flin($url,$postData);
        if($res['platRespCode']=="SUCCESS"){//成功
            $df = [
                "admin_id"=>$param["mch_id"],
                "orderno"=>$param["orderno"],
                "df_orderno"=>$param["df_orderno"],
                "df_amount"=> $param["df_amount"],
                "msg"=>"待到账",
                "add_time"=>time(),
                "notify_url"=>$param["notify_url"],
                "paymethod"=>"flinpay"
            ];
            db("df")->insert($df);//记下代付记录
            return json($res);
        }else{//失败
            $df = [
                "admin_id"=>$param["mch_id"],
                "orderno"=>$param["orderno"],
                "df_orderno"=>$param["df_orderno"],
                "df_amount"=> $param["df_amount"],
                "msg"=>$res['platRespMessage'],
                "add_time"=>time(),
                "status"=>2,
                "notify_url"=>$param["notify_url"],
                "paymethod"=>"flinpay"
            ];
            db("df")->insert($df);//记下代付记录
            return json($res);
        }
    }

    /**
     * @author ASUS
     * @date 2021-09-07 15:03
     * 代付回调
     */
    public function dfNotify()
    {
        $post = file_get_contents('php://input');//接受的post数据
        log_write("flin_df",$post);//写入日志
        $param = convert_url_query($post);
        $df_orderno = $param['orderNum'];//支付订单号
        $df = db("df")->where(["df_orderno"=>$df_orderno])->find();
        if ($param['status'] === '2') {//支付成功
            $df_data = [
                'status'=>1,
                'msg'=>"success",
                'notify_time'=>time()
            ];
            db("df")->where(["df_orderno"=>$df_orderno])->update($df_data);
        }else{//支付失败
            $df_data = [
                'status'=>0,
                'msg'=>"代付失败",
                'notify_time'=>time()
            ];
            db("df")->where(["zf_orderno"=>$df_orderno])->update($df_data);
        }
        http_post($df["notify_url"], json_encode($param));
        echo "SUCCESS";
    }
    /**
     * @author ASUS
     * @date 2020-09-15 10:25
     * flinPay支付
     */
    public function zf()
    {
        $post = file_get_contents('php://input');//接受的post数据
        $param = json_decode($post, true);//转成数组
        if(empty($param)){
            $json = [
                "status"=>-1,
                "msg"=>"参数缺失",
                "data"=>[]
            ];
            return json($json);
        }
        $config = db("product")->where(["product_name"=>"flinpay"])->find();
        $url = $config['url']."/pay";//基础请求地址
        $mchId = $config["mch_id"];//商户号
        $postData = array(
            'merchantCode' => $mchId,
            'payMoney' => $param["zf_amount"],
            'method' =>  $param["method"],
            'orderNum' =>  $param["zf_orderno"],
            'productDetail' => "Test Pay",
            'name' => $param["username"],
            'email' => $param["email"],
            'phone' => $param["telephone"],
            'dateTime' => date("YmdHis",time()),
            'expiryPeriod' => '1000',
             'notifyUrl' => "",//::todo
        );
        ksort($postData);
        $params_str = '';
        foreach ($postData as $key => $val) {
            $params_str = $params_str . $val;
        }
        $sign = $this->private_key_encrypt($params_str, $config["pri_key"]);
        $postData['sign'] = $sign;
        $res = http_post_flin($url,$postData);
        if ($res['platRespCode'] == "SUCCESS") {//成功
            $zf = [
                "admin_id"=>$param["mch_id"],
                "orderno"=>$param["orderno"],
                "zf_orderno"=>$param["zf_orderno"],
                "zf_amount"=> $param["zf_amount"],
                "zf_code"=>$res['vaNumber'],
                "username"=>$param["username"],
                "telephone"=>$param["telephone"],
                "notify_url"=>$param["notify_url"],
                "msg"=>"待支付",
                "add_time"=>time(),
                "paymethod"=>"flinpay"
            ];
            db("zf")->insert($zf);//记下代付记录
            return json($res);
        }else{//失败
            $zf = [
                "admin_id"=>$param["mch_id"],
                "orderno"=>$param["orderno"],
                "zf_orderno"=>$param["zf_orderno"],
                "zf_amount"=> $param["zf_amount"],
                "zf_code"=>$res['vaNumber'],
                "username"=>$param["username"],
                "telephone"=>$param["telephone"],
                "notify_url"=>$param["notify_url"],
                "msg"=>$res['platRespMessage'],
                "add_time"=>time(),
                "status"=>2,
                "paymethod"=>"flinpay"
            ];
            db("zf")->insert($zf);//记下代付记录
            return json($res);
        }
    }
    /**
     * @author ASUS
     * @date 2020-11-27 13:43
     * flinPay还款回调
     */
    public function zfNotify()
    {
        $post = file_get_contents('php://input');//接受的post数据
        log_write("flin_zf",$post,"pcapi");//写入日志
        $param = convert_url_query($post);
        $zf_orderno = $param['orderNum'];//支付订单号
        $zf = db("zf")->where(["zf_orderno"=>$zf_orderno])->find();
        if (($param['msg'] == "SUCCESS")) {//还款成功
            //1.更新history表
            $zf_data = [
                "msg" => "支付成功",
                "status" => 1,
                "notify_time" => time(),
            ];
            db('zf')->where(["zf_orderno"=>$zf_orderno])->update($zf_data);
        } elseif (($param['status'] == "4")) {//还款失败
            $zf_data = [
                "msg" => "支付失败",
                "notify_time" => time(),
                "status" => 2,
            ];
            db('zf')->where(["orderno" => $zf_orderno])->update($zf_data);
        }
        http_post($zf["notify_url"], json_encode($param));
        echo 'SUCCESS';
    }
}